package com.zy.batiya.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.zy.batiya.domain.Menu;
import com.zy.batiya.mapper.MenuMapper;
import com.zy.batiya.service.MenuService;

@Component
public class MenuServiceImpl implements MenuService{

	@Autowired
	private MenuMapper mapper;
	
	/**
	 * 将左菜单集合封装成树结构
	 * */
	@Override
	public List<Menu> getMenuList() throws Exception{
		// TODO Auto-generated method stub
		List<Menu> fatherList = new ArrayList<Menu>();
		try {
			List<Menu> list = mapper.getMenuList();
			Map<Integer, List<Menu>> nodeMapper = new HashMap<Integer, List<Menu>>();
			for (Menu menu : list) {
				Integer parentId = menu.getParentId();
				if (parentId == 0) {
					fatherList.add(menu);
				} else {
					List<Menu> childs = nodeMapper.get(parentId);
					if (childs == null) {
						childs = new ArrayList<Menu>();
						nodeMapper.put(parentId, childs);
					}
					childs.add(menu);
				}
			}
			for(Menu m:fatherList){
				Integer id = m.getId();
				List<Menu> l = nodeMapper.get(id);
				m.setChilds(l);
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception(e.toString());
		}
		return fatherList;
	}
}
